package com.hzlh.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

public class PropertiesUtil {
	private static Properties _prop = new Properties();

	private static String defaultFileName = "/config.properties";

	private static String baseDir = "";

	/**
	 * 读取配置文件
	 */
	public Properties readProperties() {
		try {
			InputStream in = PropertiesUtil.class.getResourceAsStream(baseDir+defaultFileName);
			BufferedReader bf = new BufferedReader(new InputStreamReader(in));
			_prop.load(bf);
			return _prop;
		} catch (IOException e) {
			System.out.println("同步数据库配置文件不存在！");
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 读取配置文件
	 */
	public Properties readProperties(String filePath) {
		try {
			InputStream in = PropertiesUtil.class.getResourceAsStream(filePath);
			BufferedReader bf = new BufferedReader(new InputStreamReader(in));
			_prop.load(bf);
			return _prop;
		} catch (IOException e) {
			System.out.println("同步数据库配置文件不存在！");
			e.printStackTrace();
			return null;
		}
	}

	/**
	 *
	 * @param fileClassPathDir 文件在classpath 下面的相对路径
	 * @return
	 */
	public Properties readFileProperties(String fileClassPathDir) {
		Properties prop = new Properties();
		try {
			InputStream in = PropertiesUtil.class.getResourceAsStream(fileClassPathDir);
			BufferedReader bf = new BufferedReader(new InputStreamReader(in));
			prop.load(bf);
		} catch (IOException e) {
			prop = new Properties();
			e.printStackTrace();
		}
		return prop;
	}

	/**
	 * 根据key读取对应的value
	 *
	 * @param key
	 * @return
	 */
	public String getProperty(String key) {
		readProperties();
		return _prop.getProperty(key);
	}

	/**
	 * 根据key读取对应的value
	 *
	 * @param key
	 * @return
	 */
	public String getProperty(String key, String fileName) {
		if (!StringUtil.isEmpty(fileName)) {
			fileName = baseDir + fileName;
		}
		readProperties(fileName);
		return _prop.getProperty(key);
	}

	/**
	 * @param filename    文件名
	 * @param propertyKey 属性名
	 * @return
	 */
	public static String getProperties(String filename, String propertyKey) {
		String propertyValue = "";
		Properties jms = new Properties();
		InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream(filename);
		try {
			jms.load(in);
			propertyValue = jms.getProperty(propertyKey);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return propertyValue;
	}

	public static PropertiesUtil getInstance() {
		return new PropertiesUtil();
	}


}
